import { CloseOutlined, PlusOutlined } from '@ant-design/icons';
import { Alert, Button, Card, Form, FormListFieldData, Input, Select, Typography } from 'antd';
import { useEffect, useState } from 'react';

interface Props {
  formRef: any;
}

const { Text } = Typography;

// 文件配置表单组件
export default (props: Props) => {
  const { formRef } = props;
  const [hasFileGroup, setHasFileGroup] = useState(false);

  // 初始化检查是否已有分组配置
  useEffect(() => {
    const initialGroup = formRef.current?.getFieldValue(['fileConfig', 'fileGroupConfig']);
    setHasFileGroup(!!initialGroup);
  }, []);

  // 表单项样式
  const formItemStyle = {
    marginBottom: 16,
    minWidth: 220,
  };

  // 添加文件分组配置
  const handleAddFileGroup = () => {
    const currentFileConfig = formRef.current?.getFieldsValue().fileConfig || {};
    if (!currentFileConfig.fileGroupConfig) {
      formRef.current?.setFieldsValue({
        fileConfig: {
          ...currentFileConfig,
          fileGroupConfig: {
            condition: '',
            groupKey: '',
            groupName: '',
          },
        },
      });
      setHasFileGroup(true);
    }
  };

  // 删除文件分组配置
  const handleRemoveFileGroup = () => {
    const currentFileConfig = formRef.current?.getFieldsValue().fileConfig || {};
    const newFileConfig = { ...currentFileConfig };
    delete newFileConfig.fileGroupConfig;
    formRef.current?.setFieldsValue({
      fileConfig: newFileConfig,
    });
    setHasFileGroup(false);
  };

  /**
   * 渲染过滤配置表单项
   */
  const renderFilterConfig = (fileField: FormListFieldData) => (
    <Form.List name={[fileField.name, 'filterConfigList']}>
      {(filterFields, { add: addFilter, remove: removeFilter }) => (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {filterFields.map((filterField) => (
            <div
              key={filterField.key}
              style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}
            >
              <Form.Item
                label="范围"
                name={[filterField.name, 'range']}
                rules={[
                  {
                    required: true,
                    message: '请选择范围',
                  },
                ]}
              >
                <Select
                  style={{
                    minWidth: 120,
                  }}
                  options={[
                    { value: 'fileName', label: '文件名称' },
                    { value: 'fileContent', label: '文件内容' },
                  ]}
                  placeholder="请选择范围"
                />
              </Form.Item>
              <Form.Item
                label="规则"
                name={[filterField.name, 'rule']}
                rules={[
                  {
                    required: true,
                    message: '请选择规则',
                  },
                ]}
              >
                <Select
                  style={{
                    minWidth: 120,
                  }}
                  options={[
                    { value: 'contains', label: '包含' },
                    { value: 'startWith', label: '前缀匹配' },
                    { value: 'endsWith', label: '后缀匹配' },
                    { value: 'regex', label: '正则' },
                    { value: 'equals', label: '相等' },
                  ]}
                  placeholder="请选择规则"
                />
              </Form.Item>
              <Form.Item
                label="值"
                name={[filterField.name, 'value']}
                style={formItemStyle}
                labelCol={{ span: 4 }}
                rules={[
                  {
                    required: true,
                    message: '请输入值',
                  },
                ]}
              >
                <Input placeholder="请输入值" />
              </Form.Item>
              <Button
                type="text"
                danger
                onClick={() => removeFilter(filterField.name)}
                icon={<CloseOutlined />}
                style={{ marginTop: 4 }}
              />
            </div>
          ))}
          <Button
            type="dashed"
            onClick={() => addFilter()}
            icon={<PlusOutlined />}
          >
            添加过滤配置
          </Button>
        </div>
      )}
    </Form.List>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      <Alert
        message="请在提交前删除为空的分组文件配置，文件路径为空（默认制作所有文件）"
        type="warning"
        closable
      />
      {/* 文件分组配置卡片 */}
      {hasFileGroup && (
        <Card
          size="small"
          title={
            <Text strong style={{ color: '#1890ff' }}>
              文件分组配置
            </Text>
          }
          headStyle={{
            backgroundColor: '#f0f9ff',
            borderBottom: '2px solid #1890ff',
          }}
          style={{ borderRadius: 8 }}
          extra={
            <CloseOutlined
              onClick={handleRemoveFileGroup}
              style={{ color: '#999', fontSize: 14, cursor: 'pointer' }}
            />
          }
        >
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            <Form.Item
              label="分组 Key"
              name={['fileConfig', 'fileGroupConfig', 'groupKey']}
              style={formItemStyle}
              labelCol={{ span: 10 }}
              rules={[
                {
                  required: true,
                  message: '请输入分组key',
                },
              ]}
            >
              <Input placeholder="分组唯一标识" />
            </Form.Item>
            <Form.Item
              label="组名"
              name={['fileConfig', 'fileGroupConfig', 'groupName']}
              style={formItemStyle}
              labelCol={{ span: 6 }}
            >
              <Input placeholder="显示用组名" />
            </Form.Item>
            <Form.Item
              label="生效条件"
              name={['fileConfig', 'fileGroupConfig', 'condition']}
              style={formItemStyle}
              labelCol={{ span: 8 }}
            >
              <Input placeholder="请输入生效条件" />
            </Form.Item>
          </div>
        </Card>
      )}

      {/* 文件配置列表 */}
      <Form.List name={['fileConfig', 'files']}>
        {(fileFields, { add: addFile, remove: removeFile }) => (
          <>
            {fileFields.map((fileField) => (
              <Card
                key={fileField.key}
                size="small"
                title={<Text strong>文件配置</Text>}
                style={{ borderRadius: 8, marginBottom: 16 }}
                extra={
                  <CloseOutlined
                    onClick={() => removeFile(fileField.name)}
                    style={{ color: '#999', fontSize: 14, cursor: 'pointer' }}
                  />
                }
              >
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                  <div style={{ display: 'flex', gap: 16 }}>
                    <Form.Item
                      label="文件路径"
                      name={[fileField.name, 'path']}
                      style={formItemStyle}
                      labelCol={{ span: 8 }}
                    >
                      <Input placeholder="请输入文件路径" />
                    </Form.Item>
                    <Form.Item
                      label="生效条件"
                      name={[fileField.name, 'condition']}
                      style={formItemStyle}
                      labelCol={{ span: 8 }}
                    >
                      <Input placeholder="请输入生效条件" />
                    </Form.Item>
                  </div>

                  <Text strong>过滤配置</Text>
                  {renderFilterConfig(fileField)}
                </div>
              </Card>
            ))}

            <Button
              type="dashed"
              onClick={() => addFile()}
              icon={<PlusOutlined />}
            >
              添加文件配置
            </Button>
          </>
        )}
      </Form.List>

      {/* 操作按钮区域 */}
      <Button
        type="primary"
        onClick={handleAddFileGroup}
        icon={<PlusOutlined />}
        disabled={hasFileGroup}
      >
        添加文件分组配置
      </Button>
      <div style={{ marginBottom: 16 }} />
    </div>
  );
};
